package com.cyl.manager.act.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.ApiModelProperty;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.h5.config.SecurityUtil;
import com.cyl.manager.act.domain.entity.IntegralHistory;
import com.cyl.manager.act.domain.entity.MemberCoupon;
import com.cyl.manager.act.domain.vo.CouponActivityVO;
import com.cyl.manager.act.mapper.IntegralHistoryMapper;
import com.cyl.manager.act.mapper.MemberCouponMapper;
import com.cyl.manager.lbs.domain.LbsZbjl;
import com.cyl.manager.lbs.mapper.LbsZbjlMapper;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.mapper.ProductMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.entity.MemberAccount;
import com.cyl.manager.ums.mapper.MemberAccountMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.IDGenerator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.server.Mem;
import com.ruoyi.livesass.ProductVideoService;
import com.volcengine.model.livesaas.response.GetActivityAllCouponsPickDataResponse.AllActivityCouponPickData;
import com.volcengine.model.livesaas.response.GetActivityAllCouponsPickDataResponse.GetActivityAllCouponsPickDataResponseBody;
import com.volcengine.model.livesaas.response.GetActivityCouponPickDataResponse.ActivityCouponPickData;
import com.volcengine.model.livesaas.response.GetActivityCouponPickDataResponse.GetActivityCouponPickDataResponseBody;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.cyl.manager.act.mapper.CouponActivityMapper;
import com.cyl.manager.act.domain.entity.CouponActivity;
import com.cyl.manager.act.domain.entity.CouponCategory;
import com.cyl.manager.act.domain.query.CouponActivityQuery;
import org.springframework.transaction.annotation.Transactional;

/**
 * 优惠券活动表Service业务层处理
 *
 * @author zcc
 */
@Service
public class CouponActivityService {
    @Autowired
    private CouponActivityMapper couponActivityMapper;
    @Autowired
    private MemberCouponMapper memberCouponMapper;
    @Autowired
    private MemberMapper memberMapper;
    
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MemberAccountMapper memberAccountMapper;
    @Autowired
    private IntegralHistoryMapper integralHistoryMapper;

    @Autowired
    private ProductVideoService productVideoService;
    
    @Autowired
    private CouponCategoryService couponCategoryService;
    @Autowired
    private LbsZbjlMapper lbsZbjlMapper;
    
    @Autowired
    private CouponActivityService couponActivityService;
    
    @Autowired
    private RedisCache redisCache;
    
    
  
    
    /**
     * 	查询总数
     *
     * @param id 优惠券活动表主键
     */
    public CouponActivity selectCountByActivityId(Long id) {
        couponActivityMapper.receiveCoupon(id);
		return selectById(id);
    }
    /**
     * 查询优惠券活动表
     *
     * @param id 优惠券活动表主键
     * @return 优惠券活动表
     */
    public CouponActivity selectById(Long id) {
        return couponActivityMapper.selectById(id);
    }

    /**
     * 查询优惠券活动表列表
     * 1.需要返回直播间名称	 2.需要增加查询条件 福利券分类categoryid
     * @param query 查询条件
     * @param page  分页条件
     * @return 优惠券活动表
     */
    public Page<CouponActivityVO> selectList(CouponActivityQuery query, Pageable page) {
        PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(),"create_time desc");
        QueryWrapper<CouponActivity> qw = new QueryWrapper<>();
        Long qrDeptZbjId = query.getDeptZbjId();
        if(qrDeptZbjId!=null) {
            qw.eq("dept_zbj_id", qrDeptZbjId);
        }
        String title = query.getTitle();
        if (!StringUtils.isEmpty(title)) {
            qw.like("title", "%".concat(title.trim()).concat("%"));
        }
        Integer useScope = query.getUseScope();
        if (useScope != null) {
            qw.eq("use_scope", useScope);
        }
        
        Long deptDpId = query.getDeptDpId();
        if (deptDpId != null) {
            qw.eq("dept_dp_id", deptDpId);
        }
        
        
        Integer couponType = query.getCouponType();
        if (couponType != null) {
            qw.eq("coupon_type", couponType);
        }
        Long zbjlid = query.getZbjlid();
        if (zbjlid != null) {
            qw.eq("zbjlid", zbjlid);
        }
        
        Long categoryid = query.getCategoryid();
        if (categoryid != null) {
            qw.eq("categoryid", categoryid);
        }

        List<CouponActivity> list = couponActivityMapper.selectList(qw);
        if (CollectionUtil.isEmpty(list)) {
            return new PageImpl<>(Collections.emptyList(), page, 0);
        }
        long total = ((com.github.pagehelper.Page) list).getTotal();
        List<CouponActivityVO> resList = new ArrayList<>();
        //查找已使用张数
        Map<Long, Integer> useCountMap = memberCouponMapper.countUseCoupon((list.stream().map(it -> it.getId()).collect(Collectors.toSet()))).stream().collect(Collectors.toMap(it -> it.getId(), it -> it.getUseCount()));
        Map<Long, LbsZbjl> mapLbsZbjl = new HashMap<Long, LbsZbjl>();

        for (CouponActivity couponActivity : list) {
            CouponActivityVO vo = new CouponActivityVO();
            Map<String, Object> pmap = new HashMap<String, Object>();
            Long zbjlid1 = vo.getZbjlid();
            if(zbjlid1!=null) {
            	if(!mapLbsZbjl.containsKey(zbjlid1)) {
            		mapLbsZbjl.put(zbjlid1, lbsZbjlMapper.selectById(zbjlid1));
            	}
        		pmap.put("lbsZbjl", mapLbsZbjl.get(zbjlid1));
            }
            vo.setParams(pmap);
            BeanUtils.copyProperties(couponActivity, vo);
            Integer integer = useCountMap.get(couponActivity.getId());
            vo.setUseCount(integer == null ? 0 : integer);
            resList.add(vo);
        }
        return new PageImpl<>(resList, page, total);
    }


    public CouponActivityVO getDetail(Long id) {
        CouponActivity couponActivity = couponActivityMapper.selectById(id);
        CouponActivityVO res = new CouponActivityVO();
        BeanUtils.copyProperties(couponActivity,res);
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", SecurityUtil.getLocalMember().getId())
                .eq("coupon_activity_id", id);
        Integer count = memberCouponMapper.selectCount(queryWrapper);
        if (count != null && count >= couponActivity.getUserLimit()) {
            res.setCanGet(false);
        } else {
            res.setCanGet(true);
        }
        return res;
    }

    /**
     * 新增优惠券活动表
     *
     * @param couponActivity 优惠券活动表
     * @return 结果
     */
    public int insert(CouponActivity couponActivity) {
    	
    		couponActivity.setCouponAmount(new BigDecimal(0.01d));
        	couponActivity.setUserLimit(1);
        	couponActivity.setBeginTime(LocalDateTime.now());

        	if(couponActivity.getQlx().intValue() == 2) {
        		  QueryWrapper<CouponActivity> qw = new QueryWrapper<>();
            	  qw.eq("qlx", 2);// 1福利券 2时长券
            	  qw.eq("zbjlid", couponActivity.getZbjlid());
            	  Integer count =  couponActivityMapper.selectCount(qw);
            	 if(count!=null && count.intValue() >0 ) {
         	        throw new RuntimeException("操作失败！此次直播间时长券已添加! ");
            	 }
        	}else {
        		int ul = couponActivity.getUserLimit();
        		if(ul!=1) {
         	        throw new RuntimeException("操作失败！福利券每人限领1张! ");
        		}
        		couponActivity.setGksc(100000);
        	}
        	
        	Long id = productVideoService.createActivityCouponsFlq(couponActivity.getZbjlid(), couponActivity.getCategoryid(), couponActivity.getTotalCount(),couponActivity.getQlx(),couponActivity.getGksc());
        	couponActivity.setId(id);
            couponActivity.setLeftCount(couponActivity.getTotalCount());
            couponActivity.setCreateTime(LocalDateTime.now());
            couponActivity.setPublishstatus(9);//未发送
    		if(2 == couponActivity.getQlx().intValue()) {
    			 couponActivity.setPublishstatus(1);//发送中
        	} 
    		couponActivity.setCreateBy(SecurityUtils.getUserId());
    		couponActivity.setDeptZbjId(SecurityUtils.getDeptZbjId());
            return couponActivityMapper.insert(couponActivity);
   
    	
    }

    /**
     * 修改优惠券活动表
     *
     * @param couponActivity 优惠券活动表
     * @return 结果
     */
    public int update(CouponActivity couponActivity) {
    	productVideoService.updateActivityCouponFlq(couponActivity.getZbjlid(), couponActivity.getId(), couponActivity.getCategoryid(), couponActivity.getTotalCount(),couponActivity.getQlx(),couponActivity.getGksc());
        CouponActivity dbActivity = couponActivityMapper.selectById(couponActivity.getId());
        if (dbActivity == null) {
            return 0;
        }
//        if(2 == couponActivity.getQlx().intValue()) {
//    		LbsZbjl lbsZbjl = 	lbsZbjlMapper.selectById(couponActivity.getZbjlid());
//    		lbsZbjl.setHlqid(couponActivity.getId());
//    		lbsZbjl.setHlqsj(couponActivity.getGksc()+"");
//    	}
        couponActivity.setLeftCount(dbActivity.getLeftCount());
        couponActivity.setUpdateTime(LocalDateTime.now());
        return couponActivityMapper.updateById(couponActivity);
    }
    //上架
	public int sendById(Long id) {
		CouponActivity couponActivity = couponActivityMapper.selectById(id);
		Long zbjid = couponActivity.getZbjlid();
		if(zbjid == null) {
	        throw new RuntimeException("请设置直播间id");
		}
	    if(1 == couponActivity.getQlx().intValue()) {
			productVideoService.sendActivityCoupon(zbjid, id);
	  	}
		couponActivity.setPublishstatus(1);
		couponActivity.setUpdateTime(LocalDateTime.now());
		int num = couponActivityMapper.updateById(couponActivity);
        return num;
	}
 
	
    //同步已经领取的优惠券
	public int synById(Long id) {
		CouponActivity couponActivity = couponActivityMapper.selectById(id);
		Long zbjid = couponActivity.getZbjlid();
        return satrtGetActivityCouponPickData(id,zbjid,couponActivity.getTotalCount());
	}
	
	
	
	//下架
	public int stopById(Long id) {
		couponActivityMapper.receiveCoupon(id);
		
		CouponActivity couponActivity = couponActivityMapper.selectById(id);
		Long zbjid = couponActivity.getZbjlid();
		if(zbjid == null) {
	        throw new RuntimeException("请设置直播间id");
		}
		if(1 == couponActivity.getQlx().intValue()) {
			productVideoService.stopActivityCoupon(zbjid, id);
			// satrtGetActivityCouponPickData(id,zbjid,couponActivity.getTotalCount());
	  	}
		couponActivity.setPublishstatus(0);
		couponActivity.setUpdateTime(LocalDateTime.now());
        return couponActivityMapper.updateById(couponActivity);
	}
	
	

    /**
     * 删除优惠券活动表信息
     *
     * @param id 优惠券活动表主键
     * @return 结果
     */
    public int deleteById(Long id) {
		CouponActivity couponActivity = couponActivityMapper.selectById(id);
		Long zbjid = couponActivity.getZbjlid();
		if(zbjid != null) {
	    	productVideoService.deleteActivityCouponsFlq(zbjid,id);
		}
        return couponActivityMapper.deleteById(id);
    }

    public Page<CouponActivityVO> selectListByH5(Pageable page) {
        PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        QueryWrapper<CouponActivity> qw = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        qw.lt("begin_time", now)
                .gt("end_time", now);
        List<CouponActivity> list = couponActivityMapper.selectList(qw);
        if (CollectionUtil.isEmpty(list)) {
            return new PageImpl<>(Collections.emptyList(), page, 0);
        }
        long total = ((com.github.pagehelper.Page) list).getTotal();
        //看用户已领取的张数
        Set<Long> ids = list.stream().map(it -> it.getId()).collect(Collectors.toSet());
        Map<Long, Integer> countMap = memberCouponMapper.countGetCoupon(ids, SecurityUtil.getLocalMember().getId()).stream().collect(Collectors.toMap(it -> it.getId(), it -> it.getGetCount()));
        List<CouponActivityVO> resList = new ArrayList<>();
        for (CouponActivity it : list) {
            CouponActivityVO vo = new CouponActivityVO();
            BeanUtils.copyProperties(it, vo);
            Integer integer = countMap.get(it.getId());
            if (integer == null || integer < it.getUserLimit()) {
                vo.setGetCount(integer == null ? 0 : integer);
                vo.setCanGet(true);
            } else {
                vo.setGetCount(integer);
                vo.setCanGet(false);
            }
            resList.add(vo);
        }

        return new PageImpl<>(resList, page, total);
    }

    
//    @Transactional
//    public Boolean receiveCouponByFlq(Long id,Long memberId) {
//        CouponActivity couponActivity = couponActivityMapper.selectById(id);
//        if (couponActivity == null) {
//           throw new RuntimeException("未找到活动");
//        }
//        if (couponActivity.getQlx().intValue() == 2) {
//            throw new RuntimeException("券类型不正确");
//         }
//        //判断有没有余量
//        if (couponActivity.getLeftCount() < 1) {
//        	 throw new RuntimeException("活动已没有余额");
//        }
//        //活动未开始或者已经结束
//        if(couponActivity.getPublishstatus().intValue() != 1) {
//        	throw new RuntimeException("活动未开始或者已经结束");//活动未开始或者已经结束
//        }
//        //判断时间有没有超
//        LocalDateTime now = LocalDateTime.now();
//        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
//        	 throw new RuntimeException("活动已过期");
//        }
//        //判断领的有没有超
//        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("member_id", memberId)
//                .eq("coupon_activity_id", id);
//        Integer count = memberCouponMapper.selectCount(queryWrapper);
//        if (count != null && count >= 1) {
//       	 	throw new RuntimeException("你已领取");
//        }
//        //兑换券
//      
//        int saveCount = saveMemberCoupon(couponActivity, memberId,1,couponActivity.getQlx()+"","直播间领取");
//        couponActivityMapper.receiveCoupon(id);
//        return saveCount > 0;
//    }
    
    
    //店长给添加福利券给用户
    @Transactional
    public Boolean dzFfByFlq(Long id,Long memberId,int num ,Long deptDpId) {
        CouponActivity couponActivity = couponActivityMapper.selectById(id);
        if (couponActivity == null) {
           throw new RuntimeException("未找到福利券");
        }
        if (couponActivity.getQlx().intValue() == 2) {
            throw new RuntimeException("福利券不正确");
         }
        //判断有没有余量
        if (couponActivity.getLeftCount() < num) {
        	 throw new RuntimeException("福利券没有余额");
        }
        //活动未开始或者已经结束
        if(couponActivity.getPublishstatus().intValue() != 1) {
        	throw new RuntimeException("福利券未开始或者已经结束");//活动未开始或者已经结束
        }
        if(couponActivity.getDeptDpId() == null) {
       	 	throw new RuntimeException("福利券编号不正确！");
        }
        if(couponActivity.getDeptDpId().longValue() != deptDpId.longValue()) {
       	 	throw new RuntimeException("非本店铺的福利券编号！");
        }
        int  userLimit = couponActivity.getUserLimit();
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
        	 throw new RuntimeException("活动已过期");
        }
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId)
                .eq("coupon_activity_id", id);
        Integer count = memberCouponMapper.selectCount(queryWrapper);
        int  baseCount = count+num;
        if (baseCount > userLimit) {
        	if(count>0) {
           	 	throw new RuntimeException("每人最多发"+userLimit+"张,已经给他发了"+count+"张");
        	}else {
           	 	throw new RuntimeException("每人最多发"+userLimit+"张");
        	}
        }
       
        for (int i = count; i < baseCount; i++) {
        	boolean bool = saveMemberCoupon(couponActivity, memberId,(i+1),couponActivity.getQlx()+"","店长发放")> 0;
            couponActivityMapper.receiveCoupon(id);

		}
        return true;
    }
//    public static void main(String[] args) {
//    	 int num = 1;
//    	 Integer count = 0;
//         int  baseCount = count+num;
//        
//        
//         for (int i = count; i < baseCount; i++) {
//          System.out.println((i+1));
// 		}
//	}
    
    @Transactional
    public Boolean receiveCouponByTb(Long id,Long memberId) {
        CouponActivity couponActivity = couponActivityMapper.selectById(id);
        if (couponActivity == null) {
           // throw new RuntimeException("未找到活动");
        	return false;
        }
        if (couponActivity.getQlx().intValue() == 2) { // 1福利券 2时长券
            // throw new RuntimeException("券类型不正确");
        	return false;
         }
        //判断有没有余量
        if (couponActivity.getLeftCount() < 1) {
        	return false;
        	// throw new RuntimeException("活动已没有余额");
        }
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
        	return false;
        	// throw new RuntimeException("活动已过期");
        }
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId)
                .eq("coupon_activity_id", id);
        Integer count = memberCouponMapper.selectCount(queryWrapper);
        if (count != null && count >= 1) {
        	return false;
        }
        //兑换券
        
        int saveCount = saveMemberCoupon(couponActivity, memberId,1,couponActivity.getQlx()+"","直播间系统补发");
        couponActivityMapper.receiveCoupon(id);
        return saveCount > 0;
    }
    
    
    
//    @Transactional
//    public Map<String, Object> receiveCouponScq(Long id,Long memberId) {
//    	Map<String, Object> map = new HashMap<String, Object>();
//    	map.put("zt", false);
//
//        CouponActivity couponActivity = couponActivityMapper.selectById(id);
//        if (couponActivity == null) {
//            throw new RuntimeException("未找到活动");//中文不能变
//        }
//        if (couponActivity.getQlx().intValue() == 1) {
//            throw new RuntimeException("券类型不正确");//中文不能变
//         }
//        //判断有没有余量
//        if (couponActivity.getLeftCount() < 1) {
//            throw new RuntimeException("活动已没有余额");//中文不能变
//        }
//      //活动未开始或者已经结束
//        if(couponActivity.getPublishstatus().intValue() != 1) {
//        	throw new RuntimeException("活动未开始或者已经结束");//活动未开始或者已经结束
//        }
//        //判断时间有没有超
//        LocalDateTime now = LocalDateTime.now();
//        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
//            throw new RuntimeException("活动已过期");//中文不能变
//        }
//        //判断领的有没有超
//        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("member_id", memberId)
//                .eq("coupon_activity_id", id);
//        Integer count = memberCouponMapper.selectCount(queryWrapper);
//       
//        
//        boolean sfgxGgkkssj = false;//是否跟新开始时长
//        Long zbjlid = couponActivity.getZbjlid();
//        String memberKey = "ZBJ_GKSC_"+zbjlid+"_"+memberId;
//        
//        //时长券
//    	Long gkkssj =  redisCache.getCacheObject(memberKey);
//		int  dbgksc = couponActivity.getGksc();
//    	if(gkkssj==null || gkkssj.longValue() == 0L) {
//    		map.put("zt", false);
//        	map.put("gksc", 0);
//        	map.put("dbgksc", dbgksc);
//        	map.put("msg", "观看时长只有"+0+"分钟！，不足"+dbgksc+"分钟！");
//        	return map;
//    	}
//		long thisTime = System.currentTimeMillis();
//		int gksc = (int) (((thisTime-gkkssj)/1000)/60);
//		
//    	if(dbgksc > gksc) {
//        	map.put("zt", false);
//        	map.put("gksc", gksc);
//        	map.put("gkscTime", thisTime-gkkssj);
//        	map.put("dbgksc", dbgksc);
//        	map.put("msg", "观看时长只有"+gksc+"分钟！，不足"+dbgksc+"分钟！");
//        	return map;
//    	    // throw new RuntimeException("观看时长只有"+gksc+"分钟！，不足"+gksc+"分钟！");
//    	}else {
//    		sfgxGgkkssj = true;//是否跟新开始时长
//    	}
//   
//    	
//        if (count != null && count >= couponActivity.getUserLimit()) {
//        	map.put("count", count);
//        	return map;
//        }
//     
////        //如果是积分兑换
////        if (Objects.equals(2, couponActivity.getCouponType())) {
////            //判断积分是否够
////            MemberAccount memberAccount = memberAccountMapper.selectById(memberId);
////            if (memberAccount.getIntegralBalance().compareTo(couponActivity.getUseIntegral()) < 0) {
////                throw new RuntimeException("您的积分不足");
////            }
////
////            //扣除积分
////            memberAccountMapper.updateIntegral(couponActivity.getUseIntegral(), memberId);
////            //记录日志
////            insertIntegralHistory(couponActivity.getUseIntegral(), couponActivity.getCouponAmount(), memberId);
////        }
//
//        
//        int saveCount = saveMemberCoupon(couponActivity, memberId,1,couponActivity.getQlx()+"","直播间领取");
//      //兑换券
//        couponActivityMapper.receiveCoupon(id);
//        if(sfgxGgkkssj) {
//            redisCache.setCacheObject(memberKey, System.currentTimeMillis(),60*5,TimeUnit.MINUTES);
//        }
//        map.put("zt", saveCount > 0);
//        if(saveCount > 0) {
//        	map.put("count", count+1);
//        }
//        return map;
//    }
// 
    
    
    @Transactional
    public int saveMemberCouponExcel(CouponActivity activity, Long memberId,Integer count,String lx,String bz) {
        MemberCoupon memberCoupon = new MemberCoupon();
        memberCoupon.setCouponActivityId(activity.getId());
        memberCoupon.setTitle(activity.getTitle());
        memberCoupon.setUseScope(activity.getUseScope());
        memberCoupon.setProductIds(activity.getProductIds());
        memberCoupon.setCouponAmount(activity.getCouponAmount());
        memberCoupon.setMinAmount(activity.getMinAmount());
        memberCoupon.setUseIntegral(activity.getUseIntegral());
        memberCoupon.setCouponType(activity.getCouponType());
        memberCoupon.setBeginTime(LocalDateTime.now());
        memberCoupon.setEndTime(activity.getEndTime());
        memberCoupon.setCreateTime(LocalDateTime.now());
        memberCoupon.setMemberId(memberId);
        memberCoupon.setAmkey(memberId+"_"+activity.getId()+"_"+count);
        memberCoupon.setUseStatus(0);
        memberCoupon.setDeptZbjId(activity.getDeptZbjId());
        memberCoupon.setCouponCategoryId(activity.getCategoryid()); 
        memberCoupon.setLx(lx); //券类型 1福利券 2时长券
        memberCoupon.setBz(bz); //券类型 1福利券 2时长券
        Member member =  memberMapper.selectById(memberId);
        if(member==null) {
        	return 0;
        }
        memberCoupon.setDeptZbjId(member.getDeptZbjId());
        memberCoupon.setDeptTzId(member.getDeptTzId());
        memberCoupon.setDeptDpId(member.getDeptDpId());
        int num =  memberCouponMapper.insert(memberCoupon);
		couponActivityMapper.receiveCoupon(activity.getId());
        return num;
    }
    
    
    public int saveMemberCoupon(CouponActivity activity, Long memberId,Integer count,String lx,String bz) {
    	
        Member member =  memberMapper.selectById(memberId);
        if(member==null) {
        	return 0;
        }
        MemberCoupon memberCoupon = new MemberCoupon();
        memberCoupon.setCouponActivityId(activity.getId());
        memberCoupon.setTitle(activity.getTitle());
        memberCoupon.setUseScope(activity.getUseScope());
        memberCoupon.setProductIds(activity.getProductIds());
        memberCoupon.setCouponAmount(activity.getCouponAmount());
        memberCoupon.setMinAmount(activity.getMinAmount());
        memberCoupon.setUseIntegral(activity.getUseIntegral());
        memberCoupon.setCouponType(activity.getCouponType());
        memberCoupon.setBeginTime(LocalDateTime.now());
        memberCoupon.setEndTime(activity.getEndTime());
        memberCoupon.setCreateTime(LocalDateTime.now());
        memberCoupon.setMemberId(memberId);
        memberCoupon.setAmkey(memberId+"_"+activity.getId()+"_"+count);
        memberCoupon.setUseStatus(0);
        memberCoupon.setDeptZbjId(activity.getDeptZbjId());
        memberCoupon.setCouponCategoryId(activity.getCategoryid()); 
        memberCoupon.setLx(lx); //券类型 1福利券 2时长券
        memberCoupon.setBz(bz); //券类型 1福利券 2时长券
        
        memberCoupon.setDeptZbjId(member.getDeptZbjId());
        memberCoupon.setDeptTzId(member.getDeptTzId());
        memberCoupon.setDeptDpId(member.getDeptDpId());
        memberCoupon.setSpreaduid(member.getSpreaduid());

        return memberCouponMapper.insert(memberCoupon);
    }

//    private void insertIntegralHistory(BigDecimal amount, BigDecimal couponAmount, Long memberId) {
//        IntegralHistory history = new IntegralHistory();
//        history.setOpType(2);
//        history.setSubOpType(22);
//        history.setAmount(amount);
//        history.setOrderAmount(couponAmount);
//        history.setMemberId(memberId);
//        history.setCreateTime(LocalDateTime.now());
//        integralHistoryMapper.insert(history);
//    }

    private int satrtGetActivityCouponPickData(final long id,final long activityId,final long totalCount) {
    	int bfs = 0;
    	return satrtThread(bfs,id,activityId, totalCount,1,2000,1);
    	
//     	 new Thread() {
//	         @Override
//	         public void run() {
//	        	 // satrtThread(id,activityId, totalCount,1,2000,1);
//	         }
//	     }.start();
    
    }
   
    private int satrtThread(int bfs,final long id,final long activityId,final long totalCount,int pageNumber,int pageSize,int num) {
    	long sleepm =  1000l;
    	try {
			Thread.sleep(sleepm);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	num = num+1;
    	int xcpageNumber = pageNumber;
    	Long tcount =  0L;
    	GetActivityCouponPickDataResponseBody responseBody = productVideoService.getGetActivityCouponPickData(id,activityId, pageNumber, pageSize);
		if(responseBody!=null) {
			 tcount =  responseBody.getTotalCount();
			 List<ActivityCouponPickData> hsData = responseBody.getActivityCouponPickData();
			 if(hsData!=null) {
				 if(hsData.size() == pageSize) {//这一页拉取完了下一次拉取下一页
					 xcpageNumber = pageNumber+1;
				 }
				 for (ActivityCouponPickData allData : hsData) {
					try {
						System.err.println("同步数据--" + JSONUtil.toJsonStr(allData));
						long memberId =  Long.parseLong(allData.getExternalUserId());

						boolean	bool = couponActivityService.receiveCouponByTb(id,memberId);
						if(bool) {
							bfs++;
						}
					} catch (Exception e) {
						
					}
				}
			 }
		}
		//2个小时最多跑几次
//		int maxNum = (int) ((2*60*60*1000)/sleepm);
//		if(num > maxNum) {
//			//2个小时到了
//			return;
//		}
		if((pageNumber*pageSize) >=  totalCount || (pageNumber*pageSize) >=  tcount) {
			//已经拉取完了
			return bfs;
		}
		return satrtThread(bfs,id,activityId, totalCount, xcpageNumber, pageSize,num); 
	
    }
    
    public int addByDp(CouponActivity couponActivity) {
        Long id = IDGenerator.generateId();
    	couponActivity.setId(id);
    	couponActivity.setQlx(1);
    	couponActivity.setUseScope(1);
    	couponActivity.setPublishstatus(1);
    	couponActivity.setBeginTime(LocalDateTime.now());
    	couponActivity.setLeftCount(couponActivity.getTotalCount());
    	
    	couponActivity.setCreateTime(LocalDateTime.now());
		couponActivity.setCreateBy(SecurityUtils.getUserId());
		couponActivity.setDeptZbjId(SecurityUtils.getDeptZbjId());
		couponActivity.setCouponAmount(new BigDecimal(0.00d));;
		couponActivity.setMinAmount(new BigDecimal(0.00d));;
		couponActivity.setUseIntegral(new BigDecimal(0.00d));;
		couponActivity.setCouponType(1);;
        return couponActivityMapper.insert(couponActivity);
    }
 
    
    public int editByDp(CouponActivity couponActivity) {
        couponActivity.setUpdateTime(LocalDateTime.now());
        return couponActivityMapper.updateById(couponActivity);
    }

    
    @Transactional
	public int editGqsj(CouponActivity couponActivity) {
        CouponActivity dbActivity = couponActivityMapper.selectById(couponActivity.getId());
        if(dbActivity == null) {
        	 throw new RuntimeException("数据不存在，或删除。");
        }
        if(couponActivity.getEndTime()==null) {
            throw new RuntimeException("延长时间不能为空");
        }
        
        UpdateWrapper<CouponActivity> updateWrapper = new UpdateWrapper<CouponActivity>();
        updateWrapper.eq("id", couponActivity.getId());
        updateWrapper.set("end_time", couponActivity.getEndTime());
        updateWrapper.set("update_time", LocalDateTime.now());

        int a =  couponActivityMapper.update(null, updateWrapper);
        
        UpdateWrapper<MemberCoupon> updateWrapper2 = new UpdateWrapper<MemberCoupon>();
        updateWrapper2.eq("coupon_activity_id", couponActivity.getId());
        updateWrapper2.set("end_time", couponActivity.getEndTime());
        int b =   memberCouponMapper.update(null, updateWrapper2);
        
        
        return a+b;
	}
    

}
